# -*- coding: UTF-8 -*-
import numpy as np


class DelayStats:
    """延迟统计类，用于记录和分析所有测试轮次的延迟数据"""
    
    def __init__(self):
        self.episode_delays = []  # 存储每个episode的延迟数据
        self.total_reward = 0
        self.episode_count = 0
        self.delay_names = {
            'migration': '迁移延迟',
            'download_time': '下载延迟', 
            'transmission': '传输延迟',
            'waiting': '等待延迟',
            'computation': '计算延迟',
            'arrange': '安排延迟',
            'scaling': '扩缩容延迟',
            'backhaul': '回程延迟'
        }
        
    def record_episode(self, episode_details, total_reward):
        """记录单个episode的延迟数据"""
        episode_delays = {
            'migration': [],
            'download_time': [],
            'transmission': [],
            'waiting': [],
            'download_size': [],
            'computation': [],
            'arrange': [],
            'scaling': [],
            'backhaul': []
        }
        
        # 收集该episode中每个step的延迟
        for step_details in episode_details:
            if step_details is not None and len(step_details) == 9:
                episode_delays['migration'].append(step_details[0] if step_details[0] is not None else 0)
                episode_delays['download_time'].append(step_details[1] if step_details[1] is not None else 0)
                episode_delays['transmission'].append(step_details[2] if step_details[2] is not None else 0)
                episode_delays['waiting'].append(step_details[3] if step_details[3] is not None else 0)
                episode_delays['download_size'].append(step_details[4] if step_details[4] is not None else 0)
                episode_delays['computation'].append(step_details[5] if step_details[5] is not None else 0)
                episode_delays['arrange'].append(step_details[6] if step_details[6] is not None else 0)
                episode_delays['scaling'].append(step_details[7] if step_details[7] is not None else 0)
                episode_delays['backhaul'].append(step_details[8] if step_details[8] is not None else 0)
        
        # 计算该episode的平均延迟
        episode_avg = {}
        for key, values in episode_delays.items():
            episode_avg[key] = np.mean(values) if values else 0
        
        self.episode_delays.append(episode_avg)
        self.total_reward += total_reward
        self.episode_count += 1
        
    def get_overall_stats(self):
        """计算所有episode的统计信息"""
        if not self.episode_delays:
            return None
            
        overall_stats = {}
        delay_types = ['migration', 'download_time', 'transmission', 'waiting', 
                      'download_size', 'computation', 'arrange', 'scaling', 'backhaul']
        
        for delay_type in delay_types:
            values = [ep[delay_type] for ep in self.episode_delays]
            overall_stats[delay_type] = {
                'mean': np.mean(values),
                'std': np.std(values),
                'min': np.min(values),
                'max': np.max(values)
            }
        
        return overall_stats
    
    def print_evaluation_report(self):
        """输出详细的评估报告"""
        stats = self.get_overall_stats()
        if not stats:
            print("无延迟数据可报告")
            return
        
        print("\n" + "=" * 80)
        print("任务调度性能评估报告")
        print("=" * 80)
        
        print(f"总Episodes数量: {self.episode_count}")
        print(f"平均Episode奖励: {self.total_reward / self.episode_count:.4f}")
        print(f"总奖励: {self.total_reward:.4f}")
        
        print("\n延迟性能指标详解:")
        print("-" * 80)
        print("1. 迁移延迟: 任务从一个节点迁移到另一个节点的时间")
        print("2. 下载延迟: 容器层下载所需的总时间")
        print("3. 传输延迟: 用户上传任务数据到节点的传输时间") 
        print("4. 等待延迟: 任务在队列中等待调度的时间")
        print("5. 计算延迟: 任务实际执行计算的时间")
        print("6. 安排延迟: 任务调度和资源分配的准备时间")
        print("7. 扩缩容延迟: 容器启动和扩缩容的时间")
        print("8. 回程延迟: 任务结果从节点返回给用户的时间")
        
        print("\n延迟性能指标统计 (秒):")
        print("-" * 80)
        print(f"{'延迟类型':<15} {'平均值':<12} {'标准差':<12} {'最小值':<12} {'最大值':<12}")
        print("-" * 80)
        
        for delay_type in ['migration', 'download_time', 'transmission', 'waiting',
                          'computation', 'arrange', 'scaling', 'backhaul']:
            stat = stats[delay_type]
            name = self.delay_names[delay_type]
            print(f"{name:<15} {stat['mean']:<12.4f} {stat['std']:<12.4f} "
                  f"{stat['min']:<12.4f} {stat['max']:<12.4f}")
        
        print(f"\n平均下载大小: {stats['download_size']['mean']:.2f} MB")
        
        # 计算总延迟
        total_delay_mean = sum(stats[dt]['mean'] for dt in self.delay_names.keys())
        print(f"平均总延迟: {total_delay_mean:.4f} 秒")
        
        # 延迟占比分析
        print(f"\n延迟占比分析:")
        print("-" * 40)
        for delay_type in self.delay_names.keys():
            ratio = (stats[delay_type]['mean'] / total_delay_mean * 100) if total_delay_mean > 0 else 0
            print(f"{self.delay_names[delay_type]}: {ratio:.2f}%")
        
        print("=" * 80)
